package com.emm.yixun.website.listeners;

import com.emm.yixun.basic.service.*;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.customer.service.channel.ChannelSendHttpMessageService;
import com.emm.yixun.customer.service.impl.app.ActivitiProcessServiceImpl;
import com.emm.yixun.customer.service.impl.app.SpringWebContextUtil;
import com.emm.yixun.system.service.notice.paydeposit.PayDepositNoticeFacade;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class PayDepositListeners implements Serializable, ExecutionListener{
	private static final long serialVersionUID = -8043126878390233384L;
	
	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public void notify(DelegateExecution execution) throws Exception {
		String id=execution.getProcessBusinessKey();
		String processInstanceId=execution.getProcessInstanceId();
		PayDepositService payDepositService=getPayDepositService();
		ProjectRoomService projectRoomService=getProjectRoomService();
		PayDeposit payDeposit=payDepositService.selectById(Long.valueOf(id));
		if(payDeposit == null){
			throw new Exception("认筹记录不存在");
		}
		if(getActivitiProcessServiceImpl().isCheckPass(processInstanceId)){
			/**
			 * 1.修改认筹记录审核状态为通过   
			 * 2.记录房源变更记录
			 * 3.记录应收记录
			 * 4.更改客户交易状态为认筹，判断是否多套交易并更新状态
			 */
			//1.修改认筹记录审核状态为通过   
			PayDepositDto updateDto = new PayDepositDto();
			updateDto.setId(Long.valueOf(id));
			updateDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
			updateDto.setCheckDate(new Date());
			payDepositService.update(updateDto);
			
			//2.记录房源变更记录
			if(payDeposit.getRoomId() != null){
				RoomChangeHistoryDto dto=new RoomChangeHistoryDto();
				dto.setRoomId(payDeposit.getRoomId());
				dto.setBusinessDynamics("认筹");
				dto.setRemark("房源由【可售】转为【认筹】");
	    		dto.setMerchantId(payDeposit.getMerchantId());
	    		dto.setAccessCode(payDeposit.getAccessCode());
	    		dto.setCreateUserId(payDeposit.getCreateUserId());
	    		dto.setUserCode(payDeposit.getUserCode());
	    		dto.setDelFlag("0");
	    		dto.setBusinessHref("/customer/payDeposit/toView?id="+payDeposit.getId()+"&returnUrl=,marketing,room,index");
	    		dto.setUpdateUserId(payDeposit.getUpdateUserId());
	    		dto.setUpdateTime(new Date());
	    		RoomChangeHistoryDto rchSave=getRoomChangeHistoryService().create(dto);
	    		if(rchSave == null){
	    			throw new Exception("房源变更记录不存在");
	    		}
			}
			
			//3.记录应收记录
			NeedReceiveRefundDto needReceiveRefundDto=new NeedReceiveRefundDto();
			needReceiveRefundDto.setRelationId(payDeposit.getId());
			needReceiveRefundDto.setBusinessType("0");
			needReceiveRefundDto.setTotalReceivablesAmount(payDeposit.getPayDepositAmount());
			needReceiveRefundDto.setCustomerId(payDeposit.getCustomerId());
			needReceiveRefundDto.setRoomId(payDeposit.getRoomId());
			needReceiveRefundDto.setStatus("1");
			needReceiveRefundDto.setPostponedStatus("0");
			needReceiveRefundDto.setDocType("0");
			needReceiveRefundDto.setRemark("认筹收款");
			needReceiveRefundDto.setHousingFundType(HousingFundTypeEnum.FUNDTYPE_1.getNo());
			needReceiveRefundDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_1.getNo());
			needReceiveRefundDto.setPostponedStatus("0");
			
			needReceiveRefundDto.setMerchantId(payDeposit.getMerchantId());
			needReceiveRefundDto.setUserCode(payDeposit.getUserCode());
			needReceiveRefundDto.setAccessCode(payDeposit.getAccessCode());
			needReceiveRefundDto.setCreateUserId(payDeposit.getCreateUserId());
			needReceiveRefundDto.setDelFlag("0");
			needReceiveRefundDto.setUpdateUserId(payDeposit.getUpdateUserId());
			needReceiveRefundDto.setUpdateTime(new Date());
			NeedReceiveRefundDto nrrdSave=getNeedReceiveRefundService().create(needReceiveRefundDto);
			if(nrrdSave == null){
    			throw new Exception("待收/退款记录不存在");
    		}
			
			/**
			 * 4.更改客户交易状态为认筹，判断是否多套交易并更新状态 todo
			 * @param bugType 业务类型： 1 认筹、2 认购、3 签约
			 * @param busId 对应业务类型Id
			 * @param customerId 客户Id
			 * @param userId 用户Id
			 */
			getCustomerService().getCustomerEntity("1", Long.valueOf(id),payDeposit.getCustomerId() , payDeposit.getUpdateUserId());
			
			/**
			 * （认筹审核通过）推送消息到app
			 * @author ny
			 * @param param noticeType 提醒类型, noticeBusinessId 业务主键Id
			 * @return 【${auditStatus}】房号：${roomName}；客户：${customer};
			 */
			NoticeEntity noticeEntity = new NoticeEntity();
			noticeEntity.setNoticeBusinessId(payDeposit.getId());
			noticeEntity.setNoticeType("1");
			noticeEntity.setProcessInstanceId(processInstanceId);
			noticeEntity.setAudStatus("3");
			getPayDepositNoticeFacade().createPayDepositNotice(noticeEntity);

			/**
			 * 调用渠道接口
			 * @author Administrator
			 * 交易状态  1=认筹
			 */
			getChannelSendHttpMessageService().sendTransaction(payDeposit.getId(), TransTypeEnum.PAYDEPOSIT.getNo(), false);
		}else{
			/**
			 * 1.修改认筹记录审核状态为不通过
			 * 2.修改房源状态为未售或者认筹
			 */

			PayDepositDto updateDto = new PayDepositDto();
			updateDto.setId(payDeposit.getId());
			updateDto.setAuditStatus(AuditStatusEnum.REJECT.getNo());
			updateDto.setCheckDate(new Date());
			payDepositService.update(updateDto);
			
			//房源状态为未售或者认筹
//			ProjectRoomDto projectRoomDto=new ProjectRoomDto();
//			projectRoomDto.setId(payDeposit.getRoomId());
//			projectRoomDto.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());
//			projectRoomService.update(projectRoomDto);
			
			//判断是否无房认筹
			if(payDeposit.getIsPaydeposit().equals(IsPaydepositEnum.NO.getNo())){
				PayDepositDto payDepositDto = new PayDepositDto();
				payDepositDto.setM_auditStatus(" and t.audit_status in (1,3)");
				payDepositDto.setRoomId(payDeposit.getRoomId());
				List<PayDeposit> responseList = payDepositService.selectListByDto(payDepositDto);
				if(responseList == null || responseList.size() == 0){
					ProjectRoomDto projectRoomDto = new ProjectRoomDto();
					projectRoomDto.setId(payDeposit.getRoomId());
					projectRoomDto.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());//可售
					Integer responseRoomDto=projectRoomService.update(projectRoomDto);
					if(responseRoomDto < 1){
						throw new Exception("房间状态为可售出错");
					}
				}else{
					ProjectRoomDto projectRoomDto = new ProjectRoomDto();
					projectRoomDto.setId(payDeposit.getRoomId());
					projectRoomDto.setRoomStatus(RoomStatusEnum.RESERVE.getNo());//认筹
					Integer responseRoomDto=projectRoomService.update(projectRoomDto);
					if(responseRoomDto < 1){
						throw new Exception("房间状态为认筹出错");
					}
				}
			}
			
			/**
			 * （认筹审核不通过）推送消息到app
			 * @author ny
			 * @param param noticeType 提醒类型, noticeBusinessId 业务主键Id
			 * @return 【${auditStatus}】房号：${roomName}；客户：${customer};
			 */
			NoticeEntity noticeEntity = new NoticeEntity();
			noticeEntity.setNoticeBusinessId(payDeposit.getId());
			noticeEntity.setNoticeType("1");
			noticeEntity.setProcessInstanceId(processInstanceId);
			noticeEntity.setAudStatus("2");
			getPayDepositNoticeFacade().createPayDepositNotice(noticeEntity);
		}
	}
	
	private PayDepositNoticeFacade getPayDepositNoticeFacade(){
		return (PayDepositNoticeFacade)SpringWebContextUtil.getApplicationContext().getBean("payDepositNoticeFacade");
	}
	
	private ProjectRoomService getProjectRoomService(){
		return (ProjectRoomService)SpringWebContextUtil.getApplicationContext().getBean("projectRoomService");
	}
	
	private PayDepositService getPayDepositService(){
		return (PayDepositService)SpringWebContextUtil.getApplicationContext().getBean("payDepositService");
	}
	
	private CustomerService getCustomerService(){
		return (CustomerService)SpringWebContextUtil.getApplicationContext().getBean("customerService");
	}
	
	private ActivitiProcessServiceImpl getActivitiProcessServiceImpl(){
		return (ActivitiProcessServiceImpl)SpringWebContextUtil.getApplicationContext().getBean("activitiProcessServiceImpl");
	}
	
	private RoomChangeHistoryService getRoomChangeHistoryService(){
		return (RoomChangeHistoryService)SpringWebContextUtil.getApplicationContext().getBean("roomChangeHistoryService");
	}
	
	private NeedReceiveRefundService getNeedReceiveRefundService(){
		return (NeedReceiveRefundService)SpringWebContextUtil.getApplicationContext().getBean("needReceiveRefundService");
	}

	private ChannelSendHttpMessageService getChannelSendHttpMessageService(){
		return (ChannelSendHttpMessageService)SpringWebContextUtil.getApplicationContext().getBean("channelSendHttpMessageService");
	}
}
